package com.auth.Sercurity.service.impl;

import com.auth.Sercurity.mapper.DemoTaskApplyMapper;
import com.auth.Sercurity.mapper.DemoUserMapper;
import com.auth.Sercurity.model.Condition;
import com.auth.Sercurity.model.DemoTaskApply;
import com.auth.Sercurity.model.DemoUser;
import com.auth.Sercurity.service.DemoUserService;
import com.auth.Sercurity.util.SnowFlake;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

@Service
public class DemoUserServiceImpl extends ServiceImpl<DemoUserMapper,DemoUser> implements DemoUserService {

    @Resource
    DemoUserMapper demoUserMapper;

    @Resource
    DemoTaskApplyMapper demoTaskApplyMapper;

    /**
     * @author： hj
     * @version： 1.0
     * @methodDes：  分页
     * @date： 2022/4/2 22:15
     */
    @Override
    public List<DemoUser> findAll() {
        return demoUserMapper.getList();
    }

    /**
     * @author： hj
     * @version： 1.0
     * @methodDes：  启动一个流程定义
     * @date： 2022/4/3 9:33
     */
    @Override
    @Transactional
    public String startProcess(Long userId) {
        DemoTaskApply demoTaskApply=new DemoTaskApply();
        demoTaskApply.setUserId(userId);
        demoTaskApply.setBeginDate(LocalDate.of(2022,4,1));
        demoTaskApply.setEndDate(LocalDate.of(2022,4,7));
        demoTaskApply.setApplyBeginTime(LocalDateTime.now());

//        创建任务
        if (ObjectUtils.isEmpty(demoTaskApply.getId())){
            demoTaskApply.setId(SnowFlake.nextId());
        }
        demoTaskApply.setUserId(userId);
//        开启引擎
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        RuntimeService runtimeService = defaultProcessEngine.getRuntimeService();
        HashMap<String, Object> map = new HashMap<>();
        map.put("Element1",userId);
        map.put("Element2",3636);
        map.put("Element3",8080);
        map.put("Element4",3612);
        int i = demoTaskApply.getEndDate().compareTo(demoTaskApply.getBeginDate())+1;
        Condition condition = new Condition();
        condition.setNo(i);
        map.put("condition",condition);
        condition.setNo(i);
        ProcessInstance instance = runtimeService.startProcessInstanceByKey("DemoUserProcess",demoTaskApply.getId().toString(),map);
        TaskService taskService = defaultProcessEngine.getTaskService();
        Task task = taskService.createTaskQuery().taskAssignee(String.valueOf(userId)).processInstanceId(instance.getProcessInstanceId()).singleResult();
        taskService.complete(task.getId());
        if (!ObjectUtils.isEmpty(instance)){
            demoTaskApply.setTaskId(task.getProcessInstanceId());
            demoTaskApply.setStatus("审批中");
            demoTaskApplyMapper.insert(demoTaskApply);
            return "申请成功";
        }
        return "申请失败"+instance.getProcessInstanceId();
    }

    /**
     * @author： hj
     * @version： 1.0
     * @methodDes：  完成一个流程
     * @date： 2022/4/3 20:12
     */
    @Override
    public String complateInstance(String userId, String taskId) {
//        获取引擎
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
//       得到TaskService
        TaskService taskService = defaultProcessEngine.getTaskService();
        Task task = taskService.createTaskQuery().processInstanceId(taskId).taskAssignee(userId).singleResult();
        taskService.complete(task.getId());
//        查询流程实例
        HistoryService historyService = defaultProcessEngine.getHistoryService();
        HistoricProcessInstance instance = historyService.createHistoricProcessInstanceQuery()
                .processInstanceId(task.getProcessInstanceId())
                .processDefinitionKey("DemoUserProcess")
                .finished()
                .singleResult();
        if (!ObjectUtils.isEmpty(instance)){
            //        流程信息
            DemoTaskApply demoTaskApply = demoTaskApplyMapper.selectOne(new QueryWrapper<DemoTaskApply>().lambda().eq(DemoTaskApply::getTaskId, task.getProcessInstanceId()));
            demoTaskApply.setStatus("已完结");
            demoTaskApplyMapper.updateById(demoTaskApply);
        }
       return "执行完成";
    }

    /**
     * @author： hj
     * @version： 1.0
     * @methodDes：  查看流程详情
     * @date： 2022/4/3 21:12
     */
    @Override
    public String instanceDetail(String taskId) {
//        获得引擎
        ProcessEngine defaultProcessEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = defaultProcessEngine.getTaskService();
        List<Task> list = taskService.createTaskQuery()
                .processDefinitionKey("DemoUserProcess")
                .processInstanceId(taskId)
                .list();
        for (Task task : list) {
            System.out.println(task.toString());
        }
        return list.toString();
    }

    /**
     * @author： hj
     * @version： 1.0
     * @methodDes：  查看任务列表
     * @date： 2022/4/4 22:00
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public IPage<DemoTaskApply> findTaskAll(Long pageNo, Long pageSize) {
        Page<DemoTaskApply> page = new Page<>(pageNo, pageSize);
        return demoTaskApplyMapper.selectPage(page,new QueryWrapper<>());
    }

}
